package com.econ.powercloud.ems.aop;

import com.econ.powercloud.common.base.facade.enums.StatusType;
import com.econ.powercloud.common.base.facade.pojo.MsgResult;
import com.econ.powercloud.ems.constant.SysConstant;
import com.econ.powercloud.ems.util.RedisCacheUtil;
import com.econ.powercloud.powernode.gateway.base.utils.CurrentUserUtil;
import com.econ.powercloud.powernode.gateway.common.domain.UserDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * 用户操作权限控制切面
 * Created by xc on 190903.
 */
@Aspect
@Component
@Order(2)
public class UserOperateVerify {

    @Autowired
    private RedisCacheUtil redisCacheUtil;


    @Pointcut("@annotation(com.econ.powercloud.ems.aop.UserOperatePower)")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAftberReturning(Object ret){
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取当前请求对象
        UserDTO userDTO = CurrentUserUtil.get();
        if(userDTO == null){
            return MsgResult.builder().status(StatusType.NO_ENOUGH_CLEARANCE.getCode()).statusText(StatusType.NO_ENOUGH_CLEARANCE.getStatusText()).build();
        }
        Object tokenValue = redisCacheUtil.getUserOperateAccessToken(userDTO.getId());
        if(tokenValue == null){
            return MsgResult.builder().status(StatusType.NO_ENOUGH_CLEARANCE.getCode()).statusText(StatusType.NO_ENOUGH_CLEARANCE.getStatusText()).build();
        }
        if(0 == Integer.parseInt(tokenValue.toString())){
            redisCacheUtil.deleteUserOperateUserId(userDTO.getId());
        }
        //续期
        redisCacheUtil.expire(String.format(SysConstant.USER_OPERATE_TOKEN, userDTO.getId()), Long.parseLong(tokenValue.toString()));
        return joinPoint.proceed();
    }


}
